import sqlite3
import os
import re
import time
import sqlite3
from typing import List, Dict, Any, Tuple, Optional
from datetime import datetime

# 从core.logger导入get_logger函数
from ..core.logger import get_logger

# 使用get_logger函数初始化logger
logger = get_logger('agent.base_finance_query')


class BaseFinanceQuery:
    """
    基础金融查询处理类
    作为其他查询类的基类，提供通用功能
    """
    
    def __init__(self):
        """
        初始化基础金融查询处理器
        """
        # 获取数据库路径
        current_dir = os.path.dirname(os.path.abspath(__file__))
        self.db_path = os.path.join(
            os.path.dirname(os.path.dirname(current_dir)), 
            "dataset", "sqlite", "博金杯比赛数据.db"
        )
        logger.debug(f"Base finance query initialized with database: {self.db_path}")
    
    def _execute_query_with_db(self, query_func, *args, **kwargs):
        """
        执行带数据库连接的查询
        
        Args:
            query_func: 查询函数
            *args: 传递给查询函数的位置参数
            **kwargs: 传递给查询函数的关键字参数
            
        Returns:
            查询结果
        """
        conn = None
        try:
            conn = sqlite3.connect(self.db_path)
            conn.row_factory = sqlite3.Row
            cursor = conn.cursor()
            return query_func(cursor, *args, **kwargs)
        except Exception as e:
            logger.error(f"数据库查询出错: {e}")
            raise
        finally:
            if conn:
                conn.close()
                
    def _execute_query(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]:
        """
        执行SQL查询并返回结果
        
        Args:
            query: SQL查询语句
            params: 查询参数
            
        Returns:
            查询结果列表
        """
        def _query_func(cursor, query, params):
            cursor.execute(query, params)
            return [dict(row) for row in cursor.fetchall()]
        
        return self._execute_query_with_db(_query_func, query, params)